package com.senlingspace.framework.security.context;

import cn.hutool.core.util.StrUtil;
import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取用户信息
 *
 * @author lebronjames
 */
public class SecurityContextHolderExt {

    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    private static Map<String, Object> getOrCreateLocalMap() {
        Map<String, Object> objMap = THREAD_LOCAL.get();
        if (objMap == null) {
            objMap = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(objMap);
        }
        return objMap;
    }

    public static void setLocalMap(Map<String, Object> objMap) {
        THREAD_LOCAL.set(objMap);
    }

    public static void set(String key, Object value) {
        getOrCreateLocalMap().put(key, Objects.isNull(value) ? StrUtil.EMPTY : value);
    }

    public static String get(String key) {
        Object value = getOrCreateLocalMap().getOrDefault(key, StrUtil.EMPTY);
        return String.valueOf(value);
    }

    public static <T> T get(String key, Class<T> clazz) {
        Object value = getOrCreateLocalMap().getOrDefault(key, null);
        return clazz.cast(value);
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static Long getCustomerId() {
        return get("customer_id", Long.class);
    }

    public static void setCustomerId(Long customerId) {
        set("customer_id", customerId);
    }

    public static String getCustomerMobile() {
        return get("customer_phone", String.class);
    }

    public static void setCustomerMobile(String customerMobile) {
        set("customer_phone", customerMobile);
    }

    public static String getToken() {
        return get("customer_token", String.class);
    }

    public static void setToken(String token) {
        set("customer_token", token);
    }

    public static Long getShopId() {
        return get("shop_id", Long.class);
    }

    public static void setShopId(Long shopId) {
        set("shop_id", shopId);
    }

}
